<template>
  <div class="settlement-content">
    <Bread home="购物车" crumbs="订单结算" />
    <div class="deliveryAdress">
      <p class="title">确认收货地址</p>
      <div class="deliveryInfo">
        <div class="_adresstitle">
          <p class="shouhuoren">收货人信息</p>
          <p class="addAdress" @click="onAddAdressClick">新增收货地址</p>
        </div>
        <ul class="adress-list" :class="{ show: isShow }">
          <li class="_adress" :class="{ actived: accountData.selAddress === item.customerShippingId, noActived: accountData.selAddress !== item.customerShippingId }" v-for="item in accountData.addressList" :key="item.customerShippingId">
            <div class="user">
              <el-radio v-model="accountData.selAddress" :label="item.customerShippingId">
                <p class="contact-detail">
                  <span>{{ item.shippingProvince }}{{ item.shippingAddressDetail }}</span> <span>收货人:{{ item.shippingPerson }} </span>
                  <span>收货电话:{{ item.shippingMobile }}</span>
                </p>
              </el-radio>
              <span class="default-adress" v-if="item.customerShippingId === accountData.defaultAdress"> 默认地址</span>
            </div>
            <div class="btns">
              <span class="set-btn" @click="onSetDefaultClick(item)">设为默认地址</span>
              <span class="set-edit-btn" @click="onEditAdressClick(item)">编辑</span>
              <span class="set-btn" @click="onDeletAdressClick(item)">删除</span>
            </div>
          </li>
        </ul>

        <div v-if="accountData.addressList.length > 1" class="showAdress" @click="isShow = !isShow">
          <span v-if="isShow">收起地址</span>
          <span v-else>展开地址</span>
          <el-icon :class="{ arrowUp: isShow, arrowDown: !isShow }">
            <DArrowRight />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- <div class="invoiceinfo">
      <div class="invoInfocon">开票信息</div>
      <el-radio-group v-model="accountData.invoiceForm.invoiceType">
        <el-radio label="NO">无票</el-radio>
        <el-radio label="NORMAL">普通发票</el-radio>
        <el-radio label="ADDEDTAX">增值税发票</el-radio>
      </el-radio-group>
      <div class="invo-list" v-if="accountData.invoiceForm.invoiceType !== 'NO'">
        <div class="_invoice">
          <span class="publicmargin"
            >发票类型：
            {{ $formater.formatInvoType(accountData.invoiceForm.invoiceType) }}
          </span>
          <span class="publicmargin">发票内容：明细</span>
          <span class="publicmargin">发票抬头： {{ accountData.invoiceForm.invoiceTitle }}</span>
          <span>纳税人识别号：{{ accountData.invoiceForm.taxpayerId }}</span>
        </div>
        <div>
          <span class="edit_right" @click="onEditInvocieClick(accountData.invoiceForm)">修改</span>
        </div>
      </div>
    </div> -->
    <div>
      <table class="table" cellspacing="0" cellpadding="0">
        <thead class="table_header_title">
          <th>商品信息</th>
          <th>属性</th>
          <th>单价</th>
          <th>折后单价</th>
          <th>数量</th>
          <th>金额</th>
          <th>折后金额</th>
        </thead>
        <tbody class="table_tbody">
          <template v-for="item in accountData.goodsList" :key="item.cartId">
            <tr>
              <td class="noborder"></td>
            </tr>
            <tr>
              <td colspan="8" class="last">
                <div class="info">
                  <div class="order">
                    <!-- <el-checkbox class="goods-outer-checkbox" v-model="item.checked" @change="(val) =>onRowChecked(val,item)"></el-checkbox> -->
                    <span class="order-time">{{ $formater.formatDate(item.createTime) }}</span>
                    <span class="order-code">订单编号：{{ item.cartId }}</span>
                  </div>
                  <div class="supplier">
                    <img class="store-icon" src="@/assets/images/dianpuxiao.png" />
                    <span>供应商 : {{ item.supplierName }}</span>
                  </div>
                </div>
              </td>
            </tr>
            <tr class="goods" v-for="goods in item.cartItemList.slice(0, 3)" :key="goods.goodsId">
              <td class="goods-inf">
                <div class="goods-info">
                  <img class="goods-img" :src="goods.goodsImg?.split(',')[0]" />
                  <span class="goods-name">{{ goods.goodsName }}</span>
                </div>
              </td>
              <td>{{ goods.goodsSpec }}</td>
              <td>{{ goods.price }}</td>
              <td>{{ goods.discountPrice }}</td>
              <td>{{ goods.amount }}</td>
              <td>￥{{ (goods.amount * goods.price).toFixed(2) }}</td>
              <td class="goods-price last">
                ￥{{ goods.discountPrice ? (goods.amount * goods.discountPrice).toFixed(2) : '' }}
              </td>
            </tr>
            <tr>
              <td class="noborder"></td>
            </tr>
            <tr>
              <td colspan="8">
                <div class="order-remark">
                  <span class="remark">备注留言：</span>
                  <el-input class="remark-input" v-model="accountData.buyerRemark"></el-input>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>
  <div class="footer">
    <div class="footer-content">
      <div class="_right">
        <p>
          合计：
          <span class="_mount">￥ {{ totals.totalPrice.toFixed(2) }} </span>
        </p>
        <p>
          折后合计：
          <span class="_mount">￥ {{ totalPrice.totalPrice.toFixed(2) }} </span>
        </p>
        <Button label="确认提交" class="_button" type="warning" @click="onSubmitClick" />
      </div>
    </div>
  </div>
  <Address v-model:visible="addressVisible" :addressForm="accountData.addressForm" @change="addressChange" />
  <Invoive v-model:visible="invoiveVisible" :vovice="accountData.invoice" @change="invoiceChange" />
</template>
<script setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown, Plus, DArrowRight } from '@element-plus/icons-vue'
import api from '@/api'
import consts from '@/consts'
import formater from '@/formater'
import Address from '@/components/address/index.vue'
import Invoive from '@/components/invoice/index.vue'
import Bread from '@/components/bread/index.vue'
import Button from '@/components/button/button.vue'

const router = useRouter()
const route = useRoute()
const props = defineProps(['query'])

const addressVisible = ref(false)
const invoiveVisible = ref(false)
const proofVisible = ref(false)
const isShow = ref(false)

const accountData = reactive({
  info: {},
  goodsList: [],
  addressList: [],
  addressForm: {},
  invoiceForm: {
    invoiceType: ''
  },
  invoice: {},
  selAddress: '',
  defaultAdress: '',
  checkedAll: '',
  checked: '',
  orderData: {
    customerShippingDetailVo: {},
    customerInvoiceVo: {},
    subOrderReqInfos: []
  },
  buyerRemark: ''
})

const totals = computed(() => {
  return accountData.goodsList.reduce(
    (a, b) => {
      let totalPrice = (a.totalPrice += b.cartItemList.reduce((d, e) => d + e.currentPrice * e.amount, 0))
      return { totalPrice }
    },
    { totalPrice: 0 }
  )
})
const totalPrice = computed(() => {
  return accountData.goodsList.reduce(
    (a, b) => {
      let totalPrice = (a.totalPrice += b.cartItemList.reduce((d, e) => d + e.discountPrice * e.amount, 0))
      return { totalPrice }
    },
    { totalPrice: 0 }
  )
})

const isPurchase = computed(() => {
  return !!route.query.goodsId
})

const purchase = async () => {
  let params = { amount: props.query.amount, goodsSpecId: props.query.goodsSpecId, goodsId: props.query.goodsId }
  let { data, err } = await api.post(`/medinstrument/site/cart/purchase`, params)
  if (err) {
    ElMessage.error(err)
  } else {
    accountData.goodsList = data.list
  }
}

const delAdress = async (customerShippingId) => {
  let { err } = await api.post(`/medinstrument/site/customer/delShippingDetail?customerShippingId=${customerShippingId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const setDefault = async (customerShippingId) => {
  let { err } = await api.post(`/medinstrument/site/customer/setDefault?customerShippingId=${customerShippingId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const goodsData = async () => {
  let { data, err } = await api.get('/medinstrument/site/cart/getCheckedCart')
  if (err) {
    ElMessage.error(err)
  } else {
    accountData.goodsList = data.list
  }
}

const loadData = async () => {
  let { data, err } = await api.get('/medinstrument/site/customer/information')
  if (err) {
    ElMessage.error(err)
  } else {
    accountData.info = data
    accountData.addressList = data.customerShippingDetailList
    let { invoiceTitle, taxpayerId, invoiceType } = data
    accountData.invoiceForm = { invoiceTitle, taxpayerId, invoiceType }
    let defaultAdress = data.customerShippingDetailList.find((item) => item.defaultFlag === 'YES')

    accountData.selAddress = defaultAdress ? defaultAdress.customerShippingId : data.customerShippingDetailList[0].customerShippingId
    accountData.defaultAdress = defaultAdress ? defaultAdress.customerShippingId : data.customerShippingDetailList[0].customerShippingId
    accountData.orderData.customerShippingDetailVo = defaultAdress || data.customerShippingDetailList[0]
  }
}

const submitOrder = async () => {
  let { bankAccount, depositBank, invoiceTitle, invoiceType, registeredAddress, registeredPhone, taxpayerId } = accountData.info

  let { shippingAddressDetail, shippingMobile, shippingPerson, shippingProvince, shippingProvinceId } = accountData.orderData.customerShippingDetailVo

  const params = {
    customerInvoiceVo: {
      bankAccount,
      depositBank,
      invoiceTitle,
      invoiceType,
      registeredAddress,
      registeredPhone,
      taxpayerId
    },
    customerShippingDetailVo: {
      shippingAddressDetail,
      shippingMobile,
      shippingPerson,
      shippingProvince,
      shippingProvinceId
    },
    subOrderReqInfos: accountData.goodsList.map((e) => {
      return {
        supplierId: e.supplierId,
        supplierName: e.supplierName,
        orderGoodsVoList: e.cartItemList,
        buyerRemark: accountData.buyerRemark,
        payProof: e.payProof
      }
    })
  }

  let { err } = await api.post(`/medinstrument/site/order/submitOrder`, params)
  if (err) {
    ElMessage.error(err)
  } else {
    router.push({ path: '/allOrder' })
  }
}

const onAddAdressClick = () => {
  accountData.addressForm = {}
  addressVisible.value = true
}

const onEditAdressClick = (item) => {
  accountData.addressForm = Object.assign({}, item)
  addressVisible.value = true
}

const onSetDefaultClick = (item) => {
  setDefault(item.customerShippingId)
}

const onDeletAdressClick = (item) => {
  ElMessageBox.confirm(`您确认要删除吗(不可恢复)?`, '系统提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  })
    .then(() => {
      delAdress(item.customerShippingId)
    })
    .catch(() => {})
}

const onEditInvocieClick = (item) => {
  accountData.invoice = Object.assign({}, item)
  invoiveVisible.value = true
}

const invoiceChange = () => {
  loadData()
}

const addressChange = () => {
  loadData()
}

const checkedAllChange = () => {
  accountData.goodsList.forEach((item) => {
    item.checked = accountData.checkedAll
  })
}

const onSubmitClick = () => {
  submitOrder()
}

onMounted(() => {
  loadData()
  isPurchase.value ? purchase() : goodsData()
})
</script>

<style lang="scss" scoped>
.settlement-content {
  width: 1080px;
  margin: 10px auto;

  .addAdress,
  .edit_right {
    font-size: 12px;
    color: #08a28c;
    cursor: pointer;
    line-height: 20px;
  }

  .deliveryAdress {
    .title {
      line-height: 22px;
      font-size: 16px;
      color: var(--span-color-text);
      font-weight: 500;
    }

    .deliveryInfo {
      position: relative;
      border: 1px solid #ccc;
      margin-top: 10px;
      padding: 20px;

      ._adresstitle {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .shouhuoren {
          line-height: 20px;
          font-weight: 500;
        }

        .addAdress,
        .edit_right {
          font-size: 12px;
          color: #08a28c;
          cursor: pointer;
          line-height: 20px;
        }
      }

      ._adresstitle:hover {
        .addadress {
          display: block;
        }

        .addAdress:hover {
          color: #e89000;
        }
      }

      .adress-list {
        height: 30px;
        overflow: hidden;

        &.show {
          height: auto;
        }

        ._adress {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 30px;
          padding: 5px 20px 5px 20px;
          border: 1px solid var(--border-color);
          margin-bottom: 10px;
          font-size: 12px;
          font-weight: 500;
          box-sizing: border-box;

          .user {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .default-adress {
              display: block;
              width: 55px;
              height: 20px;
              line-height: 20px;
              font-size: 12px;
              background-color: #3e424c;
              color: #ffffff;
              text-align: center;
            }
          }
        }
        ._adress:hover,
        ._adress.actived {
          border: 1px solid var(--color-primary);
        }
        ._adress.actived {
          background: #fff9ee;
        }

        ._adress.actived:hover {
          .set-edit-btn {
            display: inline-block;
          }
        }

        ._adress.noActived:hover {
          .set-edit-btn {
            display: inline-block;
          }

          .set-btn {
            display: inline-block;
          }
        }

        .contact-detail {
          font-size: 12px;
          font-weight: 700;

          span {
            display: inline-block;
            margin-right: 10px;
          }
        }

        .btns {
          display: flex;
          align-items: center;
          cursor: pointer;

          .set-edit-btn {
            display: none;
            color: #08a28c;
            height: 20px;
            line-height: 20px;
          }

          .set-btn {
            display: none;
            color: #08a28c;
            margin-left: 20px;
          }

          .set-btn:first-child {
            margin-right: 20px;
          }
        }
      }

      .showAdress {
        display: flex;
        align-items: center;

        cursor: pointer;
        font-size: 12px;
        color: var(--span-color-text);
        line-height: 20px;
        font-weight: 500;
        margin-top: 10px;

        .arrowUp,
        .arrowDown {
          margin-left: 10px;
        }

        .arrowUp {
          transform: rotate(-90deg);
          transition: 0.2s;
        }

        .arrowDown {
          transform: rotate(90deg);
          transition: 0.2s;
        }
      }
    }
  }

  .invoiceinfo {
    border: 1px solid #ccc;
    margin-top: 10px;
    padding: 20px;
    margin-bottom: 20px;

    .invoInfocon {
      font-weight: 500;
      line-height: 20px;
      margin-bottom: 10px;
    }

    .invo-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 5px 24px;
      margin-top: 10px;
      border: 1px solid var(--color-primary);
      background: #fff9ee;
      font-size: 12px;

      ._invoice {
        .publicmargin {
          margin-right: 40px;
        }
      }
    }
  }

  .table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 20px;

    th {
      width: 160px;
    }
    .table_header_title {
      height: 42px;
      background-color: var(--color-background);
      color: var(--span-color-text);

      margin-bottom: 20px;
    }

    .table_tbody {
      // position: relative;

      td.noborder {
        border: 0;
        height: 20px;
      }

      td.noborder:first-child {
        border-left: none;
      }

      tr {
        td {
          line-height: 18px;
          text-align: center;
        }

        td:first-child {
          border-left: 1px solid rgba(228, 231, 237, 1);
        }

        td.last {
          border-right: 1px solid rgba(228, 231, 237, 1);
        }
      }

      .order-remark {
        display: flex;
        width: 100%;
        height: 80px;
        background: #f9f9f9;
        padding: 12px 0 0 20px;
        box-sizing: border-box;
        position: relative;

        span {
          font-size: 12px;
        }

        .remark-input {
          width: 900px;
          height: 46px;
          margin-left: 15px;
        }
      }

      .order-remark::before {
        content: '';
        position: absolute;
        top: 0;
        left: 5%;
        width: 15px;
        height: 15px;
        background-color: #f9f9f9;
        transform: rotate(-45deg) translateY(-10px);
      }

      .info {
        display: flex;
        align-items: center;
        padding: 12px 0 12px 10px;
        height: 42px;
        box-sizing: border-box;
        border-top: 1px solid var(--border-color);
        background-color: #f9f9f9;

        .order,
        .supplier {
          display: flex;
          align-items: center;
          height: 18px;
          line-height: 18px;
        }

        .order {
          .goods-outer-checkbox {
            width: 14px;
            height: 14px;
          }

          .order-time {
            margin: 0 12px;
          }

          .order-code {
            color: var(--span-color-text);
            font-weight: 500;
          }
        }

        .supplier {
          margin-left: 90px;

          .store-icon {
            width: 20px;
            height: 20px;
            margin: 0 7px 0 11px;
          }
        }
      }

      .goods {
        .goods-inf {
          padding: 20px 20px 20px 54px;
        }

        td {
          border-bottom: 1px solid rgba(228, 231, 237, 1);

          .goods-info {
            display: flex;
            align-items: center;

            .goods-img {
              display: inline-block;
              width: 72px;
              height: 72px;
              margin-right: 12px;
            }

            .goods-name {
              width: 180px;
            }
          }

          .goods-price {
            font-weight: 600;
            color: var(--color-primary);
            border-right: 1px solid;
          }

          .el-input-number :deep(.el-input--small) {
            width: 80px;
            height: 25px;
          }

          .el-input-number--small {
            width: 80px;
            height: 25px;

            :deep(.el-input-number__decrease),
            :deep(.el-input-number__increase) {
              width: 22px;
              height: 22px;
              box-sizing: border-box;
            }
          }
        }
      }

      .el-button {
        width: 76px;
        height: 30px;
        line-height: 18px;
      }
    }
  }
}

.footer {
  position: sticky;
  bottom: 0;
  height: 50px;
  box-shadow: 0px -4px 12px 0px rgba(0, 0, 0, 0.04);
  border-bottom: 1px solid var(--border-color);
  background: #fff;
  z-index: 2;
  .footer-content {
    width: 1080px;
    margin: 0 auto;
    display: flex;
    justify-content: flex-end;

    ._right {
      display: flex;
      justify-content: flex-end;
      align-items: center;

      p {
        margin-right: 20px;
      }

      ._mount {
        font-size: 18px;
        color: var(--color-primary);
        line-height: 18px;
        font-weight: 600;
      }

      ._button {
        margin-left: 12px;
        width: 112px;
        height: 50px;
        background: var(--color-primary);
        color: #fff;
        font-size: 20px;
        font-weight: 500;
        border: none;

        &.disabled {
          background: #ccc;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
